/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Bean;

import Action.EventSessionBeanLocal;
import Entity.Category;
import Entity.Event;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author Cyrax
 */
@ManagedBean
@SessionScoped
public class EventBean {

    @EJB
    private EventSessionBeanLocal eventSessionBean;
    private Event event;
    private Category cat;
    private List<Event> ev;
    private int catId;
    private Event selectEvent;
    private String info;

//    @ManagedProperty(value = "#{categoryBean}")//this is used to pass value from accountBean to businessBean
//    CategoryBean catBean;
    /** Creates a new instance of EventBean */
    public EventBean() {
        event = new Event();
    }

    /**
     * @return the event
     */
    public Event getEvent() {
        return event;
    }

    /**
     * @param event the event to set
     */
    public void setEvent(Event event) {
        this.event = event;
    }

    public List<Event> getListEvent() {

        try {
            ev = eventSessionBean.ListAllEvent();
            System.out.println("hello:" + ev);

        } catch (Exception e) {
            System.out.println("Eror list category : " + e.getMessage());
        }
        return ev;
    }

    /**
     * @return the cat
     */
    public Category getCat() {
        return cat;
    }

    /**
     * @param cat the cat to set
     */
    public void setCat(Category cat) {
        this.cat = cat;
    }

    //Insert event
    public void insertEvent() {

        try {
            cat = new Category();
            cat.setCategoryId(catId);
            event.setEventImg(filePath);
            event.setCategory(cat);
            eventSessionBean.insertEvent(event);
            System.out.println("Xem Id:" + event.getCategory().getCategoryId());
            System.out.println("Xem Img:" +event.getEventImg());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    //update event
    public void updateEvent() {

        cat = new Category();
        cat.setCategoryId(catId);
        int eventId = event.getEventId();
        event.setEventImg(filePath);
        event.setCategory(cat);
//            String file=getFilePath();
//            file=event.getEventImg();
        System.out.println("Xem Event:" + eventId);
        System.out.println("Xem category:" + event.getCategory().getCategoryId());
        System.out.println("Xem Image:" + event.getEventImg());
        System.out.println("Xem Image:" + event.getEventInfo());
        System.out.println("Xem Image:" + event.getEventTitle());
        System.out.println("Xem Image:" + event.getReleaseDate());
        System.out.println("Xem Image:" + event.getEndDate());
        System.out.println("Xem Image:" + event.getDuration());

        eventSessionBean.eventsUpdate(eventId, event.getCategory().getCategoryId(), event.getEventTitle(), event.getEventInfo(), event.getEventImg(), event.getReleaseDate(), event.getDuration(), event.getEndDate());

    }
    //delete event

    public void deleteEvent(Event event) {

        try {

            eventSessionBean.deleteEvent(event);
        } catch (Exception e) {
            System.out.println("Error : " + e.getMessage());
        }
    }
    //UPLOAD IMAGES
    FacesContext contexts = FacesContext.getCurrentInstance();
    ExternalContext extcontexts = FacesContext.getCurrentInstance().getExternalContext();
    HttpSession session = (HttpSession) contexts.getExternalContext().getSession(true);
    FacesContext context = FacesContext.getCurrentInstance();
    Map map = context.getExternalContext().getRequestParameterMap();
    private String filePath = "image_01.jpg";
    private static final int BUFFER_SIZE = 6124;

    public void handleFileUpload(FileUploadEvent event) {

        String uploadedFolder = FacesContext.getCurrentInstance().getExternalContext().getInitParameter("uploadFolder");

        ExternalContext extContext = FacesContext.getCurrentInstance().
                getExternalContext();
        File result = new File(extContext.getRealPath("//" + uploadedFolder) + "//" + event.getFile().getFileName());
        System.out.println(result.getAbsolutePath());

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(result);

            byte[] buffer = new byte[BUFFER_SIZE];

            int bulk;
            InputStream inputStream = event.getFile().getInputstream();
            while (true) {
                bulk = inputStream.read(buffer);
                if (bulk < 0) {
                    break;
                }
                fileOutputStream.write(buffer, 0, bulk);
                fileOutputStream.flush();
            }

            fileOutputStream.close();
            inputStream.close();

            filePath = uploadedFolder + "/" + event.getFile().getFileName();

            FacesMessage msg = new FacesMessage("Succesful",
                    event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);

        } catch (IOException e) {
            e.printStackTrace();

            FacesMessage error = new FacesMessage("The files were not uploaded!");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }

    /**
     * @return the filePath
     */
    public String getFilePath() {

        return filePath;
    }

    /**
     * @param filePath the filePath to set
     */
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    /**
     * @return the catId
     */
    public int getCatId() {
        return catId;
    }

    /**
     * @param catId the catId to set
     */
    public void setCatId(int catId) {
        this.catId = catId;
    }

    /**
     * @return the selectEvent
     */
    public Event getSelectEvent() {
        return selectEvent;
    }

    /**
     * @param selectEvent the selectEvent to set
     */
    public void setSelectEvent(Event selectEvent) {
        this.selectEvent = selectEvent;
    }

    public String Substring(String evInfo) {

        if (event.getEventInfo().toString().length() > 40) {
            evInfo = event.getEventInfo().toString().substring(0, 20);
        }
        return evInfo;
    }
    private String msTitle;

    public void checkEventTitle() {
        if (eventSessionBean.checkEventTitle(event.getEventTitle())) {
            setMsTitle("This Event Title is already existed");
        } else {
            setMsTitle("");

        }
    }

    /**
     * @return the msTitle
     */
    public String getMsTitle() {
        return msTitle;
    }

    /**
     * @param msTitle the msTitle to set
     */
    public void setMsTitle(String msTitle) {
        this.msTitle = msTitle;
    }
}
